package com.dins.elashutina.parser;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: ekaterina.lashutina
 * Date: 09.09.13
 * Time: 12:08
 */
public class CoberturaParser {

    static String path = "";

    public static Tree startCoberturaParser(File fileName, Tree tree) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.replaceAll("\t", "");
                coberturaParse(line,tree);
            }
            return tree;
        } catch (FileNotFoundException e) {
            System.out.println("File not found" + fileName);
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Exception");
            e.printStackTrace();
        }
        return tree;
    }

    public static void coberturaParse(String line, Tree tree) {
        if (line.startsWith("<package ") || line.startsWith("<class ") || line.startsWith("<method ") || line.startsWith("<coverage")) {
            String[] tmp = line.split("\"");
            String newpath = "";
            newpath += "\\" + tmp[1];
            List<String> args = new ArrayList<String>();
            if (line.startsWith("<coverage")) {
                newpath = "\\coverage";
                args.add(tmp[1]);
                args.add(tmp[3]);
            } else if (line.startsWith("<package")) {
                args.add(tmp[3]);
                args.add(tmp[5]);
            } else if (line.startsWith("<class")) {
                newpath += ".java";
                args.add(tmp[5]);
                args.add(tmp[7]);
            } else if (line.startsWith("<method")) {
                args.add(tmp[5]);
                args.add(tmp[7]);
            }
            if (tree.isEmpty()) {
                tree.setRoot(new Node(newpath, path + newpath, args, null));
            } else {
                tree.add(new Node(newpath, path + newpath, args, tree.getNode(path)));
            }
            path += newpath;
        } else if (line.startsWith("</package>") || line.startsWith("</class>") || line.startsWith("</method>") || line.startsWith("</coverage>")) {
            //
            String[] tmp = path.split("\\\\");
            path = "";
            for (int i = 1; i < tmp.length - 1; i++) {
                path += "\\" + tmp[i];
            }
        } else return;
    }
}
